import md5 from 'utils/md5.js';
export default {
	request,
	InitGlobalData,
	ActivityRequest,
	getNewObj
}

function InitGlobalData() {
	let globalData = getApp().globalData;
	if (!globalData.ticket) {
		globalData.ticket = uni.getStorageSync('ticket');
		globalData.ZpAppId = uni.getStorageSync('ZpAppId');
		globalData.Customer = uni.getStorageSync('Customer');
		globalData.UserInfo = uni.getStorageSync('UserInfo');
		globalData.MallDomain="http://"+globalData.Customer.CustDomain+'.'+globalData.MallDomain;
		globalData.WebDomain="http://"+globalData.Customer.CustDomain+'.member.onlyid.cn/#/';
	}
}

//http 请求类, 当noRefech为true时，不做未授权重试机制
function request(params, noRefetch) {
	let globalData = getApp().globalData;
	let url = globalData.MobileApi + params.url;
	if (!params.type) {
		params.type = 'get';
	}
	/*不需要再次组装地址*/
	if (params.setUpUrl == false) {
		url = params.url;
	}

	let ticket = "Bearer ";
	if (globalData.ticket) ticket = ticket + globalData.ticket;
	if (!params.hideLoading) uni.showLoading({
		title: '加载中',
		mask: true
	});
	uni.request({
		url: url,
		data: params.data,
		method: params.type,
		dataType: 'json',
		crossDomain: true,
		xhrFields: {
			withCredentials: true
		},
		header: {
			'content-type': 'application/json',
			'Authorization': ticket
		},
		success: function(res) {
			if (!params.hideLoading) uni.hideLoading();
			// 判断以2（2xx)开头的状态码为正确
			// 异常不要返回到回调中，就在request中处理，记录日志并showToast一个统一的错误即可
			var code = res.statusCode.toString();
			var startChar = code.charAt(0);
			if (startChar == '2') {
				params.sCallback && params.sCallback(res.data);
			} else {
				if (code == '401' || code == '403') {
					if (!noRefetch) {
						that._refetch(params);
					}
					uni.showToast({
						icon: 'none',
						title: '网络异常,请稍后重试'
					});
				}
				params.sCallback && params.sCallback(res.data);
			}
		},
		fail: function(err) {
			uni.showToast({
				icon: 'none',
				title: '网络异常,请稍后重试'
			});
		}
	});
}

//http 请求类, 当noRefech为true时，不做未授权重试机制
function ActivityRequest(params, noRefetch) {
	let globalData = getApp().globalData;
	let url = globalData.ActivityMobileApi + params.url;
	if (!params.type) {
		params.type = 'get';
	}
	/*不需要再次组装地址*/
	if (params.setUpUrl == false) {
		url = params.url;
	}

	let ticket = "Bearer ";
	if (globalData.ticket) ticket = ticket + globalData.ticket;
	if (!params.hideLoading) uni.showLoading({
		title: '加载中',
		mask: true
	});
	uni.request({
		url: url,
		data: getNewObj(params.data),
		method: params.type,
		dataType: 'json',
		crossDomain: true,
		xhrFields: {
			withCredentials: true
		},
		header: {
			'content-type': 'application/json',
			'Authorization': ticket
		},
		success: function(res) {
			if (!params.hideLoading) uni.hideLoading();
			// 判断以2（2xx)开头的状态码为正确
			// 异常不要返回到回调中，就在request中处理，记录日志并showToast一个统一的错误即可
			var code = res.statusCode.toString();
			var startChar = code.charAt(0);
			if (startChar == '2') {
				params.sCallback && params.sCallback(res.data);
			} else {
				if (code == '401' || code == '403') {
					if (!noRefetch) {
						that._refetch(params);
					}
					uni.showToast({
						icon: 'none',
						title: '网络异常,请稍后重试'
					});
				}
				params.sCallback && params.sCallback(res.data);
			}
		},
		fail: function(err) {
			uni.showToast({
				icon: 'none',
				title: '网络异常,请稍后重试'
			});
		}
	});
}

//ActivityMobileApi调用格式化参数
function getNewObj(obj) {
	var encodeUnicode = function(str) {
		var res = [];
		for (var i = 0; i < str.length; i++) {
			if (str.charCodeAt(i) > 32 && str.charCodeAt(i) < 127)
				res[i] = str[i];
			else
				res[i] = "\\u" + (("00" + str.charCodeAt(i).toString(16)).slice(-4));
		}
		return res.join("");
	}

	var timeSpan = (new Date()).valueOf(); //时间戳
	obj.timeSpan = timeSpan;
	var newKey = Object.keys(obj).sort();
	var res = "";
	for (var i = 0; i < newKey.length; i++)
		res += newKey[i] + "=" + obj[newKey[i]] + "&";
	var signStr = res + "SignSecretKey=6c452c890f995b08548497c371bfb539";
	signStr = encodeUnicode(signStr);
	console.log(signStr);
	var md5sign = md5.hex_md5(md5.hex_md5(signStr));
	obj.sign = md5sign;
	console.log(md5sign);
	return obj;
}
